#!/bin/bash
FILE_NAME=$1
STR=`sed -n '1p' ./${FILE_NAME}`
TEMP_STR=($STR)
BLOCKCHAIN_NAME=${TEMP_STR[1]}
STR=`sed -n '3p' ./${FILE_NAME}`
TEMP_STR=($STR)
CRYTPO_PATH=${TEMP_STR[1]}

COUNT_ADD_PEERS=`expr $# - 1`
COUNT_ADD_PEERS=`expr ${COUNT_ADD_PEERS}  / 2`
STR=$@
ARG_ARR=($STR)
function addPeers(){
	for ((i=1;i<`expr ${COUNT_ADD_PEERS} + 1`;i++));do
	PEER_NAME=${ARG_ARR[i]}
	ARRAY=(${PEER_NAME//-/ })
	ORG_NAME=${ARRAY[1]}
	
    echo "  ${ARG_ARR[i]}: #TAGPEERS:_${ORG_NAME}" > temp.txt
    

    echo "    url: ${ARG_ARR[`expr ${COUNT_ADD_PEERS} + $i`]}  #TAGPEERS:_${ORG_NAME}

    grpcOptions: #TAGPEERS:_${ORG_NAME}
      ssl-target-name-override: ${ARG_ARR[i]} #TAGPEERS:_${ORG_NAME}
      keep-alive-time: 0s #TAGPEERS:_${ORG_NAME}
      keep-alive-timeout: 20s #TAGPEERS:_${ORG_NAME}
      keep-alive-permit: false #TAGPEERS:_${ORG_NAME}
      fail-fast: false #TAGPEERS:_${ORG_NAME}
      allow-insecure: false #TAGPEERS:_${ORG_NAME}

    tlsCACerts: #TAGPEERS:_${ORG_NAME}
      path: ${CRYTPO_PATH}/peerOrganizations/${ORG_NAME}/tlsca/tlsca.${ORG_NAME}-cert.pem #TAGPEERS:_${ORG_NAME}" >> temp.txt
	line=`sed -n '$=' ${FILE_NAME}`
	#line2=`sed -n '$=' ${FILE_NAME}`
	line2=`sed -n "/peers:    #${ORG_NAME}/=" ${FILE_NAME} | tail -n1`
  	line2=`expr ${line} + 1`
	sed -i "${line} r temp.txt" ${FILE_NAME}
	
 	done	
	for ((i=1;i<`expr ${COUNT_ADD_PEERS} + 1`;i++));do
	PEER_NAME=${ARG_ARR[i]}
	ARRAY=(${PEER_NAME//-/ })
	ORG_NAME=${ARRAY[1]}
	echo "      - ${ARG_ARR[i]} #TAGORGS:_${ORG_NAME}" > temp2.txt    
	line2=`sed -n "/peers:    #${ORG_NAME}/=" ${FILE_NAME} | tail -n1`
  	#line2=`expr ${line2} + 1`
  	sed -i "${line2} r temp2.txt" ${FILE_NAME}
	done
	rm -rf temp.txt
	rm -rf temp2.txt
}
addPeers
